package me.chan.helper;

import me.chan.annotation.Action;
import me.chan.entity.Handler;
import me.chan.entity.Request;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by JanGin on 2017/6/21.
 *
 * the class is used to store the map relation between request and handler
 */
public class ControllerHelper {

    private static final Map<Request, Handler> ACTION_MAP = new HashMap<>();

    static {
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();

        if (CollectionUtils.isNotEmpty(controllerClassSet)) {

            for (Class<?> controllerClass :controllerClassSet) {

                Method[] methods = controllerClass.getDeclaredMethods();

                if (ArrayUtils.isNotEmpty(methods)) {

                    for (Method method : methods) {
                        //if the action annotation exists, then parses it
                        if (method.isAnnotationPresent(Action.class)) {
                            Action action = method.getAnnotation(Action.class);
                            String mappingUri = action.value();
                           if (mappingUri.matches("\\w+:\\w*")) {
                                String[] mapping = mappingUri.split(":");
                               if (ArrayUtils.isNotEmpty(mapping) && mapping.length == 2) {
                                   String requestMethod = mapping[0];
                                   String requestUri = mapping[1];
                                   //init the request
                                   Request request = new Request(requestMethod, requestUri);
                                    //init the handler
                                   Handler handler = new Handler(controllerClass, method);

                                   ACTION_MAP.put(request, handler);
                               }
                           }
                        }
                    }
                }
            }
        }
    }


    public static Handler getHandler(String requestMethod, String requestPath) {
        Request req = new Request(requestMethod, requestPath);
        return ACTION_MAP.get(req);
    }

    public static Handler getHandler(Request request) {
        if (ACTION_MAP.containsKey(request)) {
            return ACTION_MAP.get(request);
        }
        return null;
    }

}
